package com.mySampleApplication.client.codeRule;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.mySampleApplication.client.CodeRuleAtter.CodeRuleAtter;
import com.mySampleApplication.client.CodeRuleAtter.CodeRuleAtterService;
import com.mySampleApplication.client.History.HistoryWindow;
import com.mySampleApplication.client.components.SDialog;
import com.mySampleApplication.client.dmp.DmpDto;
import com.mySampleApplication.client.dmp.DmpService;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.SelectionAppearance;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.util.BooleanCallback;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.*;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.CellClickEvent;
import com.smartgwt.client.widgets.grid.events.CellClickHandler;
import com.smartgwt.client.widgets.grid.events.SelectionUpdatedEvent;
import com.smartgwt.client.widgets.grid.events.SelectionUpdatedHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.tree.TreeNode;

import java.util.*;

public class CodeRule {
    private static ListGrid plistGrid;


    public static ListGrid getPlistGrid() {
        return plistGrid;
    }

    public static void setPlistGrid(ListGrid plistGrid) {
        CodeRule.plistGrid = plistGrid;
    }

    public static Map<String,Object> getListGrid() {
        Map<String,Object> map =new HashMap<>();
        // 创建一个列表网格控件
        ListGrid listGrid =getOp();

        ListGrid finalListGrid = listGrid;
        listGrid.setWidth100(); // 设置宽度为100%
        listGrid.setHeight100(); // 设置高度为100%
//        listGrid.setWidth(1024);
//        listGrid.setHeight(224);
        // 设置列表网格显示网格线
        listGrid.setShowAllRecords(false); // 显示所有记录
        // 开启分页功能
        listGrid.setDataPageSize(10); // 每页显示的数据条数
        //listGrid.setShowFilterEditor(true); // 显示过滤编辑器
//        listGrid.setSelectionType(SelectionStyle.MULTIPLE);//开启多选框
        //listGrid.setShowRowNumbers(true); // 显示行号
        //listGrid.setPaginationMode(PaginationMode.LOCAL); // 设置分页模式为本地分页
        //允许用户编辑行内容
        //listGrid.setCanEdit(true);
        //listGrid.setEditEvent(ListGridEditEvent.DOUBLECLICK); // 双击进行编辑
        listGrid.setModalEditing(true);
        listGrid.setVirtualScrolling(false);
        listGrid.setShowRecordComponents(true);
        listGrid.setShowRecordComponentsByCell(true);
        //listGrid.setCanRemoveRecords(true);
        listGrid.setCellHeight(40);
        listGrid.setHeaderHeight(50);


        ListGridField selectedCountriesField = new ListGridField("name", "Selected");
        selectedCountriesField.setWidth(70);
        listGrid.setFields(selectedCountriesField);

//        listGrid.setSelectionType(SelectionStyle.SIMPLE);
//        listGrid.setSelectionAppearance(SelectionAppearance.CHECKBOX);

        // 定义列表网格的列
        ListGridField idField = new ListGridField("id", "序号");
        // 设置自定义的 Formatter
        idField.setCellFormatter(new CustomCellFormatter());
        idField.setWidth(50);
        ListGridField db_model_idField = new ListGridField("db_model_id", "数据模型id");
        ListGridField db_model_mc = new ListGridField("db_model_name", "数据模型名称");
//        db_model_idField.setCellFormatter(new CustomCellFdmcFormatter());

        ListGridField mcField = new ListGridField("mc", "规则名称");
        mcField.setCellFormatter(new CustomCellFdmcFormatter());

        ListGridField msField = new ListGridField("ms", "规则描述");
        ListGridField fbzt = new ListGridField("fbzt", "状态");

        ListGridField fgfField = new ListGridField("fgf", "分隔符");

        ListGridField qzField = new ListGridField("qz", "前缀");

        ListGridField hzField = new ListGridField("hz", "后缀");

//        ListGridField statusField = new ListGridField("status", "状态");
        ListGridField bbField = new ListGridField("bb", "当前版本");
        bbField.setCellFormatter(new CustomCellbbFormatter());
        ListGridField actionField = new ListGridField("actionField", "操作");
        actionField.setWidth(200);
        listGrid.setFields(idField, db_model_mc,mcField,msField,fgfField, qzField,hzField,fbzt,bbField,actionField);

        // 创建按钮和事件处理
        Button addButton = new Button("Add");
        addButton.setTitle("新增");
        addButton.setIcon("[SKIN]/actions/add.png"); // 设置图标路径
        addButton.setShowRollOver(true);
        addButton.setShowDown(true);
        addButton.addClickHandler(event -> showAddDialog(finalListGrid));

        Button EditButton = new Button("Edit");
        EditButton.setTitle("编辑");
        // 禁用按钮
        EditButton.setDisabled(true);
//        EditButton.setIcon("[SKIN]/actions/edit.png"); // 设置图标路径
        EditButton.addClickHandler(event -> showEditDialog(finalListGrid));


        Button removeButton = new Button("Remove");
        removeButton.setIcon("[SKIN]/actions/remove.png"); // 设置图标路径
        removeButton.setTitle("删除");
//        removeButton.setAutoFit(true);
        // 禁用按钮
        removeButton.setDisabled(true);
        removeButton.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                ListGridRecord[] selectedRecord = finalListGrid.getSelectedRecords();
                if(selectedRecord != null && selectedRecord.length>0) {
                    Arrays.stream(selectedRecord).forEach(a->{
                        if(a.getAttribute("fbzt").equals("发布")){
                            SC.say( a.getAttribute("status"));
                            finalListGrid.removeData(a);
                            removeButton.setDisabled(true);
                            deleteRecord(a,event);
                        }else{
                            SC.say( "状态为发布的编码规则不可进行删除！");
                        }

                    });

                } else {
                    SC.say("Select a record before performing this action");
                }
            }

        });

        // 添加 CellClickHandler 处理单击事件
        listGrid.addCellClickHandler(new CellClickHandler() {
            @Override
            public void onCellClick(CellClickEvent event) {
                // 获取单击发生的行和列
                int rowNum = event.getRowNum();
                int colNum = event.getColNum();

                // 判断是否单击了指定的列
                if (colNum == listGrid.getFieldNum("mc")) {
                    // 获取单击处的数据
                    ListGridRecord record = listGrid.getRecord(rowNum);
//                    String value = record.getAttribute("fdmc");
//                    SC.say( "弹窗显示详情！"+record.getAttribute("id"));
                    details(record,listGrid,true);
                    // 执行其他操作...
                }else if(colNum == listGrid.getFieldNum("bb")){
                    ListGridRecord record = listGrid.getRecord(rowNum);
                    HistoryWindow.getShowWindow(1200,500,"历史版本",record).show();
                }
            }
        });

        //单选事件
        listGrid.addSelectionUpdatedHandler(new SelectionUpdatedHandler() {
            public void onSelectionUpdated(SelectionUpdatedEvent event) {
                if(listGrid.getSelectedRecords().length>0){
                    removeButton.setDisabled(false);
                    if(listGrid.getSelectedRecords().length==1){
                        EditButton.setDisabled(false);
                    }else {
                        EditButton.setDisabled(true);
                    }
                }else {
                    removeButton.setDisabled(true);
                    EditButton.setDisabled(true);
                }
                //SC.say(listGrid.getSelectedState());
            }
        });

        setPlistGrid(listGrid);
        map.put("listGrid",listGrid);
        //map.put("buttonLayout",buttonLayout);
        return map;

    }

    private static ListGrid getOp(){
        return new ListGrid() {
            @Override
            protected Canvas createRecordComponent(final ListGridRecord record, Integer colNum) {

                String fieldName = this.getFieldName(colNum);

                if (fieldName.equals("actionField")) {
                    HLayout recordCanvas = new HLayout(3);
                    recordCanvas.setHeight(22);
                    recordCanvas.setWidth100();
                    recordCanvas.setAlign(Alignment.CENTER);

                    IButton fdImg = new IButton();
                    fdImg.setTitle("分段配置");
                    fdImg.setWidth(65);
                    fdImg.addClickHandler(new ClickHandler() {
                        public void onClick(ClickEvent event) {
                            createSidePanel(record,event);
                            //SC.say("Edit Comment Icon Clicked for country : " + record.getAttribute("id"));
                        }
                    });
                    IButton jyStatusImg = new IButton();
                    jyStatusImg.setTitle("禁用");
                    jyStatusImg.setWidth(50);
                    jyStatusImg.addClickHandler(new ClickHandler() {
                        public void onClick(ClickEvent event) {
                            SC.ask("是否禁用该编码规则?", new BooleanCallback() {
                                public void execute(Boolean value) {
                                    if (value != null && value) {
                                        updateStatus(record,event);
                                    }
                                }
                            });
                        }
                    });

                    IButton qyStatusImg = new IButton();
                    qyStatusImg.setTitle("启用");
                    qyStatusImg.setWidth(50);
                    qyStatusImg.addClickHandler(new ClickHandler() {
                        public void onClick(ClickEvent event) {
                            if(record.getAttribute("fbzt").equals("未发布")){
                                SC.warn("请先发布该编码规则！");
                            }else{
                                SC.ask("是否启用该编码规则?", new BooleanCallback() {
                                    public void execute(Boolean value) {
                                        if (value != null && value) {
                                            updateStatus(record,event);
                                        }
                                    }
                                });
                            }
                        }
                    });
                    if(record.getAttribute("fbzt").equals("禁用")){
                        recordCanvas.addMember(qyStatusImg);
                    }else if(record.getAttribute("fbzt").equals("发布")){
                        recordCanvas.addMember(jyStatusImg);
                    }

                    recordCanvas.setHeight(22);
                    recordCanvas.setWidth100();
                    recordCanvas.setAlign(Alignment.CENTER);
                    if(record.getAttribute("fbzt").equals("未发布")){
                        IButton editImg = new IButton();
                        editImg.setTitle("编辑");
//                        editImg.setIcon("[SKIN]/actions/edit.png"); // 设置图标路径
                        editImg.setWidth(60);
                        editImg.addClickHandler(new ClickHandler() {
                            public void onClick(ClickEvent event) {
                                editRecord(record,getPlistGrid(),false);
                                //SC.say("Edit Comment Icon Clicked for country : " + record.getAttribute("id"));
                            }
                        });

                        recordCanvas.addMember(editImg);
                    }else {
                        IButton sbImg = new IButton();
                        sbImg.setTitle("升版");
                        sbImg.setWidth(60);
                        sbImg.addClickHandler(new ClickHandler() {
                            public void onClick(ClickEvent event) {
                                editRecord(record,getPlistGrid(),false);
                                //SC.say("Edit Comment Icon Clicked for country : " + record.getAttribute("id"));
                            }
                        });
                        recordCanvas.addMember(sbImg);
                    }

//                    recordCanvas.addMember(hqbmImg);

                    IButton chartImg = new IButton();
                    chartImg.setTitle("删除");
                    chartImg.setWidth(60);
                    chartImg.addClickHandler(new ClickHandler() {
                        public void onClick(ClickEvent event) {
                            SC.ask("该操作会删除该编码规则的所有数据！是否删除该条数据?", new BooleanCallback() {
                                public void execute(Boolean value) {
                                    if (value != null && value) {
                                        deleteRecord(record,event);
                                    } else {

                                    }
                                }
                            });
                        }
                    });

                    recordCanvas.addMember(chartImg);
                    return recordCanvas;
                } else {
                    return null;
                }
            }
        };
    }

    private static void showqDialog(ListGrid listGrid) {
        Dialog dialog = SDialog.createDialog(1400,650,"表单组件", null,listGrid);
        dialog.show();
    }

    public static void showAddDialog(ListGrid listGrid) {
        DmpService.App.getInstance().getDataElementCategoryList(new AsyncCallback<DmpDto>() {
            public void onSuccess(DmpDto dmpDto) {
                List<Map<String, String>> keyValueMap = dmpDto.getKeyValueListMap();
                TreeNode[] employeeData = new TreeNode[1];
                int i=0;
                for (Map<String, String> data : keyValueMap) {
                    employeeData[i]= new EmployeeTreeNode(data.get("id"),data.get("parent_id"),data.get("name"));
                    i++;
                }
                Window dialog =dataObjectwindow.getShowWindow(1200,550,"选择数据对象",null,listGrid,employeeData,null,null);
                dialog.show();
            }
            public void onFailure(Throwable caught) {
                SC.warn("获取数据失败！");
            }
        });

    }

    // 自定义的 Formatter
    private static class CustomCellFormatter implements com.smartgwt.client.widgets.grid.CellFormatter {
        @Override
        public String format(Object value, ListGridRecord record, int rowNum, int colNum) {
            return Integer.toString(rowNum + 1); // 返回当前行的序号（行号）
        }
    }

    private static void showEditDialog(ListGrid listGrid) {
        ListGridRecord selectedRecord = listGrid.getSelectedRecord();
        if (selectedRecord != null) {
            //Dialog dialog = SDialog.createDialog("Edit Item", selectedRecord,listGrid);
            Window dialog=CodeRuleWindow.getShowWindow(0,1000,350,"编辑编码规则", selectedRecord,listGrid,false,"","","","",null);
            dialog.show();
        } else {
            SC.say("Please select an item to edit.");
        }
    }

    // 编辑记录函数
    private static void editRecord(ListGridRecord record, ListGrid listGrid,boolean istrue) {
        Window bmgf = CodingSpecificationwindow.getShowWindow(800,390,"(2/5)编辑编码规范",record,listGrid,"","");
        bmgf.draw();

    }

    // 详情
    private static void details(ListGridRecord record, ListGrid listGrid,boolean istrue) {
        Window dialog=CodeRuleWindow.getShowWindow(0,1000,650,"编码规则详情", record,listGrid,istrue,"","","","xq",null);
        dialog.show();
        // 执行编辑操作
    }

    // 升版记录函数
    private static void sbRecord(ListGridRecord record, ClickEvent event,boolean istrue) {
        Window dialog=SbWindow.getShowWindow(1,1000,350,"编码规则升版", record,getPlistGrid(), istrue);
        dialog.show();
        // 执行编辑操作
    }

    // 删除记录函数
    private static void deleteRecord(ListGridRecord record, ClickEvent event) {
        ListGrid listGrid = getPlistGrid();
        if(!record.getAttribute("fbzt").equals("发布")){
                int num = Integer.parseInt(record.getAttribute("bb"));
                num=num-1;
                Map<String, String> map = new HashMap<>();
                map.put("id", record.getAttribute("id"));
                map.put("coderule_id", record.getAttribute("id"));
                map.put("bb",num+"");
                CodeRuleService.App.getInstance().deleteCodeRuleVersion(map,new AsyncCallback<String>() {
                    public void onSuccess(String result) {
                    }
                    public void onFailure(Throwable caught) {
                        SC.warn("RPC failed");
                    }
                });

                // 执行删除操作
                CodeRuleAtterService.App.getInstance().deleteByCoderuleId(record.getAttribute("id"),new AsyncCallback<String>() {
                    public void onSuccess(String result) {
//                    SC.say( "删除成功！");
                        CodeRuleService.App.getInstance().deleteById(record.getAttribute("id"),new AsyncCallback<String>() {
                            public void onSuccess(String result) {
                                listGrid.removeData(record);
                                SC.say( "删除成功！");
                            }
                            public void onFailure(Throwable caught) {
                                SC.warn("RPC failed");
                            }
                        });
                    }
                    public void onFailure(Throwable caught) {
                        SC.warn("RPC failed");
                    }
                });
//            }

        }else{
            SC.say( "状态为发布的编码规则不可进行删除！");
        }

    }


    public static void createSidePanel(ListGridRecord record, ClickEvent event) {
        Window dialog=FdpzWindow.getShowWindow(1200,700,"分段配置",record);
        dialog.show();
        // 执行分段配置操作
    }
    // 修改状态
    public static void updateStatus(ListGridRecord record, ClickEvent event) {
        Map<String, String> map = new HashMap<>();
        ListGrid listGrid = getPlistGrid();

        Map<String, String> mapPage = new HashMap<>();
        mapPage.put("pageSize", "1");
        mapPage.put("pageNumber", "10");
        map.put("id", record.getAttribute("id"));
        if(record.getAttribute("fbzt").equals("禁用")){
            map.put("fbzt","发布");
        }else{
            map.put("fbzt","禁用");
        }
        CodeRuleService.App.getInstance().setStatus(map,new AsyncCallback<String>() {
            public void onSuccess(String result) {
//                SC.say( "删除成功！");
                List<ListGridRecord> recordList = new ArrayList<>();
                CodeRuleService.App.getInstance().getSelect(new HashMap<>(), mapPage, new AsyncCallback<CodeRuleDto>() {
                    public void onSuccess(CodeRuleDto result) {
                        List<Map<String, String>> keyValueMap = result.getKeyValueMap();
                        for (Map<String, String> data : keyValueMap) {
                            ListGridRecord record = new ListGridRecord();
                            data.forEach((k, v) -> {
                                record.setAttribute(k, v);
                            });
                            // 设置其他需要的属性
                            recordList.add(record);
                        }
                        listGrid.setData(recordList.toArray(new ListGridRecord[0]));
//                        SC.say( "新增数据成功！");
                        //list.addAll(result);
                    }
                    public void onFailure(Throwable caught) {
                        SC.warn("获取数据失败！");
                    }
                });


            }
            public void onFailure(Throwable caught) {
                SC.warn("RPC failed");
            }
        });
    }

    // 自定义的 Formatter
    private static class CustomCellFdmcFormatter implements com.smartgwt.client.widgets.grid.CellFormatter {
        @Override
        public String format(Object value, com.smartgwt.client.widgets.grid.ListGridRecord record, int rowNum, int colNum) {
            return "<span style='color: blue;cursor: pointer;'>" + value + "</span>"; // 使用 HTML 标签设置字体样式
        }
    }
    // 自定义的 Formatter
    private static class CustomCellbbFormatter implements com.smartgwt.client.widgets.grid.CellFormatter {
        @Override
        public String format(Object value, com.smartgwt.client.widgets.grid.ListGridRecord record, int rowNum, int colNum) {
            return "<span style='color: #fff;\n" +
                    "    background-color: #5de55da3;\n" +
                    "    cursor: pointer;\n" +
                    "    border-radius: 3px;\n" +
                    "    /* border: 1px silver solid; */\n" +
                    "    width: 30px;\n" +
                    "    padding: 0 20px;'>" + value + "</span>"; // 使用 HTML 标签设置字体样式
        }
    }

    public static class EmployeeTreeNode extends TreeNode {
        public EmployeeTreeNode(String employeeId, String reportsTo, String name) {
            setAttribute("EmployeeId", employeeId);
            setAttribute("ReportsTo", reportsTo);
            setAttribute("Name", name);
        }
    }
}
